/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-22 09:37:51
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-05-17 09:39:29
 * @FilePath: \vite-project\src\pages\system\auth\application\Index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { type ProColumns, ProTable, type ActionType } from '@ant-design/pro-components';
import { Button, Switch, Tag, Image, Space, message, Modal } from 'antd';
import { RENT_STATUS_ENUM, RENT_TYPES_ENUM } from 'constant';
import { useRef, useState } from 'react';
import { delTenant, getRenterList, modifyValidStats } from 'apis/renter';
import CommonDrawer from 'components/common/CommonDrawer';
import ApplicationForm from 'components/operateSystem/rent/ApplicationForm';
import { Icon } from '@iconify/react/dist/iconify.js';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom-v5-compat';

export default function Renter() {
    const navigate = useNavigate();
    const [messageApi] = message.useMessage();
    const columns: ProColumns<API.TenantDetailResponseType>[] = [
        {
            title: '租户名',
            key: 'name',
            dataIndex: 'name',
            render: (_, record) => (
                <div>
                    <Tag color='processing'>{record.type === 1 ? '企业' : '政府机构'}</Tag>
                    {record.name}
                </div>
            ),
        },
        {
            title: '机构代码',
            key: 'socialOrganizationId',
            dataIndex: 'socialOrganizationId',
        },
        {
            title: '租户类型',
            key: 'type',
            dataIndex: 'type',
            valueType: 'select',
            valueEnum: RENT_TYPES_ENUM,
        },
        {
            title: '租户状态',
            key: 'validStat',
            dataIndex: 'validStat',
            valueType: 'select',
            valueEnum: RENT_STATUS_ENUM,
            render: (_, record) => (
                <Switch
                    checkedChildren='启用'
                    unCheckedChildren='禁用'
                    checked={record.validStat === 1}
                    onClick={() => onDisEnableStatus(record)}
                />
            ),
        },
        {
            title: '入驻时间',
            key: 'createTime',
            dataIndex: 'createTime',
            valueType: 'dateRange',
            render: (_, record) => {
                return record.createTime ? dayjs(Number(record.createTime)).format('YYYY-MM-DD HH:mm:ss') : '';
            },
        },
        {
            title: '证件',
            key: 'image',
            dataIndex: 'image',
            hideInSearch: true,
            render: (_, record) => {
                return (
                    <Space className='text-12px'>
                        <div className='flex flex-col items-center'>
                            {record?.tenantAttachUrl ? (
                                <Image width={30} height={30} src={record?.tenantAttachUrl} />
                            ) : (
                                <Icon icon='ant-design:close-outlined' className='w-30px h-30px bg-[#eee] text-white' />
                            )}
                            <div className='line-clamp-1'>营业执照</div>
                        </div>
                        <div className='flex flex-col items-center'>
                            {record?.enterpriseNoFontAttachUrl ? (
                                <Image width={30} height={30} src={record?.enterpriseNoFontAttachUrl} />
                            ) : (
                                <Icon icon='ant-design:close-outlined' className='w-30px h-30px bg-[#eee] text-white' />
                            )}
                            <div className='line-clamp-1'>身份证正面</div>
                        </div>
                        <div className='flex flex-col items-center'>
                            {record?.enterpriseNoFontAttachUrl ? (
                                <Image width={30} height={30} src={record?.enterpriseNoFontAttachUrl} />
                            ) : (
                                <Icon icon='ant-design:close-outlined' className='w-30px h-30px bg-[#eee] text-white' />
                            )}
                            <div className='line-clamp-1'>身份证反面</div>
                        </div>
                    </Space>
                );
            },
        },
        {
            title: '租户标签',
            key: 'tags',
            dataIndex: 'tags',
            render: (_, record) => {
                if (!record.tags) {
                    return '';
                }
                return record?.tags?.split(',')?.map((item: string, index: number) => (
                    <Space>
                        <Tag key={index} color='processing'>
                            {item}
                        </Tag>
                    </Space>
                ));
            },
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_, redord) => [
                <a key='link' onClick={() => handleEdit(redord)}>
                    修改
                </a>,
                <a key='link2' onClick={() => handleDel(redord.id)}>
                    删除
                </a>,
                // <a key="link3" onClick={() => handleApply(redord.id)}>
                // 	应用授权
                // </a>,
            ],
        },
    ];
    const [visible, setVisible] = useState<boolean>(false);
    const [editFormData, setEditFormData] = useState<API.TenantDetailFormeType>({
        type: 1,
    });
    const tableRef = useRef<ActionType>();
    const [applyId, setApplyId] = useState<string>();

    // 应用授权
    const [open, setOpen] = useState(false);

    // methods
    const refresh = () => {
        tableRef.current?.reload();
    };

    const commonAction: ({
        title,
        content,
        api,
    }: {
        title: string;
        content: string;
        api: () => Promise<any>;
        successMsg: string;
    }) => void = ({ title, content, api, successMsg }) => {
        Modal.confirm({
            title,
            content,
            okText: '确定',
            cancelText: '取消',
            centered: true,
            async onOk() {
                return new Promise<void>(async (resolve, reject) => {
                    try {
                        await api();
                        messageApi.success(successMsg);
                        resolve();
                        refresh();
                    } catch (error) {
                        reject();
                    }
                });
            },
        });
    };
    const onDisEnableStatus = (redord: API.TenantDetailResponseType) => {
        commonAction({
            title: '提示',
            content: `确定要${redord.validStat === 1 ? '禁用' : '启用'}吗`,
            api: () =>
                modifyValidStats({
                    id: redord.id,
                    validStat: redord.validStat === 1 ? 0 : 1,
                }),
            successMsg: `租户状态${redord.validStat === 1 ? '关闭' : '启用'}`,
        });
    };

    const handleAdd = () => {
        navigate(`/system/plaform/renter/form/add`);
    };

    const handleEdit = async (record: API.TenantDetailResponseType) => {
        navigate(`/system/plaform/renter/form/${record?.id}`);
    };
    const handleDel = (id?: string) => {
        commonAction({
            title: '提示',
            content: `确定要删除吗`,
            api: () =>
                delTenant({
                    id,
                }),
            successMsg: `租户确认删除`,
        });
    };
    const handleApply = (id?: string) => {
        setOpen(true);
        setApplyId(id);
    };

    return (
        <>
            <ProTable<API.TenantDetailResponseType>
                actionRef={tableRef}
                columns={columns}
                request={async (params) => {
                    let data = [];
                    let totalPages = 0;
                    const res: any = await getRenterList({
                        pageNumber: params?.current || 1,
                        pageSize: params?.pageSize || 10,
                        name: params?.name,
                        type: params?.type,
                        validStat: params?.validStat,
                        socialOrganizationId: params?.socialOrganizationId,
                        tags: params?.tags,
                        createTimeStart: params?.createTime && dayjs(params?.createTime[0]).unix(),
                        createTimeEnd: params?.createTime && dayjs(params?.createTime[1]).unix(),
                    });
                    data = res?.recordDatas || [];
                    totalPages = res?.totalPages;
                    return Promise.resolve({
                        data,
                        success: true,
                        total: totalPages,
                    });
                }}
                rowKey='id'
                pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                }}
                search={{
                    layout: 'vertical',
                    defaultCollapsed: false,
                }}
                dateFormatter='string'
                toolBarRender={() => [
                    <Button type='primary' onClick={handleAdd}>
                        新建
                    </Button>,
                ]}
            />
            <CommonDrawer isHideConfirm={true} title='应用授权' open={open} close={() => setOpen(false)}>
                <ApplicationForm
                    id={applyId}
                    close={() => {
                        setOpen(false);
                        refresh();
                    }}
                ></ApplicationForm>
            </CommonDrawer>
        </>
    );
}
